<template>
  <div class="mcp-manager">
    <div class="action-bar">
      <div class="search-wrapper">
        <div class="search-input">
          <i class="search-icon el-icon-search"></i>
          <input 
            type="text" 
            v-model="keyword" 
            placeholder="搜索MCP名称或描述" 
            @keyup.enter="handleSearch"
          />
          <button class="search-btn" @click="handleSearch">搜索</button>
        </div>
      </div>
      
      <div class="action-buttons">
        <button class="btn-primary" @click="handleCreateMcp">
          <i class="btn-icon el-icon-plus"></i>
          <span>创建MCP</span>
        </button>
      </div>
    </div>
    
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="mcpList"
        style="width: 100%"
        :header-cell-style="{
          background: '#f9fafc',
          color: '#606266',
          fontWeight: '600',
          borderBottom: '2px solid #EBEEF5'
        }"
        :cell-style="{
          padding: '12px 0'
        }"
      >
        <el-table-column prop="ID" label="ID" width="80" align="center">
          <template #default="scope">
            <span class="user-id">{{ scope.row.ID }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="describe" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <span class="type-badge" :class="row.type === 1 ? 'type-stdio' : 'type-sse'">
              {{ row.type === 1 ? 'STDIO' : 'SSE' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <span 
              class="status-badge" 
              :class="row.status === 1 ? 'status-active' : 'status-inactive'"
            >
              {{ row.status === 1 ? '已启用' : '已禁用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="cmd" label="命令" min-width="150" show-overflow-tooltip />
        <el-table-column prop="params" label="参数" min-width="120" show-overflow-tooltip />
        <el-table-column prop="env" label="环境变量" min-width="120" show-overflow-tooltip />
        <el-table-column prop="UpdatedAt" label="更新时间" min-width="180">
          <template #default="{ row }">
            {{ new Date(row.UpdatedAt).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <button 
                class="action-btn btn-info"
                @click="handleEdit(row)"
              >
                编辑
              </button>
              <button 
                class="action-btn" 
                :class="row.status === 1 ? 'btn-warning' : 'btn-success'"
                @click="handleStatusChange(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </button>
              <button 
                class="action-btn btn-danger"
                @click="handleDelete(row)"
              >
                删除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-footer">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- MCP表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      width="650px"
      destroy-on-close
      class="mcp-dialog"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <template #header>
        <div class="dialog-custom-header">
          <div class="header-title">
            <span class="title-icon"><i class="el-icon-s-tools"></i></span>
            <div class="title-content">
              <h3>{{ isEdit ? '编辑MCP' : '创建MCP' }}</h3>
              <p>{{ isEdit ? '修改MCP信息' : '添加新的MCP工具' }}</p>
            </div>
          </div>
        </div>
      </template>
      
      <div class="dialog-body">
        <!-- 表单错误提示 -->
        <div v-if="formErrors.length > 0" class="form-errors">
          <div class="error-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="error-list">
            <p v-for="(error, index) in formErrors" :key="index" class="error-item">{{ error }}</p>
          </div>
        </div>

        <el-form 
          ref="formRef"
          :model="mcpForm" 
          :rules="rules"
          label-position="top"
          class="mcp-form"
        >
          <div class="form-section">
            <div class="section-title">基本信息</div>
            <div class="form-row">
              <el-form-item label="名称" prop="name" class="form-item">
                <el-input 
                  v-model="mcpForm.name" 
                  placeholder="请输入MCP名称"
                  prefix-icon="el-icon-s-tools"
                />
              </el-form-item>
              
              <el-form-item label="描述" prop="describe" class="form-item">
                <el-input 
                  v-model="mcpForm.describe" 
                  placeholder="请输入描述"
                  prefix-icon="el-icon-document"
                />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="类型" prop="type" class="form-item">
                <el-select v-model="mcpForm.type" placeholder="请选择类型" class="full-width">
                  <el-option :value="1" label="STDIO" />
                  <el-option :value="2" label="SSE" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态" prop="status" class="form-item">
                <el-select v-model="mcpForm.status" placeholder="请选择状态" class="full-width">
                  <el-option :value="1" label="启用" />
                  <el-option :value="0" label="禁用" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          
          <div class="form-section">
            <div class="section-title">命令配置</div>
            <el-form-item label="命令" prop="cmd">
              <el-input 
                v-model="mcpForm.cmd" 
                placeholder="请输入命令"
                prefix-icon="el-icon-terminal"
              />
            </el-form-item>
            
            <el-form-item label="参数">
              <el-input 
                v-model="mcpForm.params" 
                type="textarea"
                :rows="3"
                placeholder="请输入参数，用逗号分隔"
                class="monospace-input"
              />
            </el-form-item>
            
            <el-form-item label="环境变量">
              <el-input 
                v-model="mcpForm.env" 
                type="textarea"
                :rows="3"
                placeholder="请输入环境变量，格式：KEY=VALUE，用逗号分隔"
                class="monospace-input"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitting"
          >
            {{ submitting ? '提交中...' : (isEdit ? '保存修改' : '创建MCP') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getMcpList, createMcp, updateMcp, deleteMcp, type McpInfo, type McpCreateDTO, type McpPageRequest } from '../api/mcp'

// 列表相关
const mcpList = ref<McpInfo[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 表单相关
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const submitting = ref(false)
const formErrors = ref<string[]>([])
const isEdit = ref(false)
const editId = ref<number | null>(null)

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入MCP名称', trigger: 'blur' }
  ],
  describe: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  cmd: [
    { required: true, message: '请输入命令', trigger: 'blur' }
  ]
})

// MCP表单数据
const mcpForm = ref<McpCreateDTO>({
  name: '',
  describe: '',
  type: 1,
  status: 1,
  cmd: '',
  params: '',
  env: ''
})

// 重置表单
const resetForm = () => {
  mcpForm.value = {
    name: '',
    describe: '',
    type: 1,
    status: 1,
    cmd: '',
    params: '',
    env: ''
  }
  formErrors.value = []
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 页面初始化
onMounted(() => {
  fetchMcpList()
})

// 获取MCP列表
const fetchMcpList = async () => {
  loading.value = true
  try {
    const params: McpPageRequest = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: keyword.value
    }
    const res = await getMcpList(params)
    mcpList.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    // 错误已被拦截器处理
  } finally {
    loading.value = false
  }
}

// 搜索并刷新列表
const handleSearch = () => {
  currentPage.value = 1
  fetchMcpList()
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchMcpList()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchMcpList()
}

// 创建MCP
const handleCreateMcp = () => {
  isEdit.value = false
  editId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑MCP
const handleEdit = (row: McpInfo) => {
  isEdit.value = true
  editId.value = row.ID
  
  // 填充表单数据
  mcpForm.value = {
    name: row.name,
    describe: row.describe,
    type: row.type,
    status: row.status,
    cmd: row.cmd,
    params: row.params || '',
    env: row.env || ''
  }
  
  dialogVisible.value = true
}

// 修改MCP状态
const handleStatusChange = async (row: McpInfo) => {
  const newStatus = row.status === 1 ? 0 : 1
  try {
    await updateMcp(row.ID, {
      ...row,
      status: newStatus
    })
    row.status = newStatus
    ElMessage.success(`MCP已${newStatus === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    // 错误已被拦截器处理
  }
}

// 删除MCP
const handleDelete = (row: McpInfo) => {
  ElMessageBox.confirm(
    `确定要删除MCP "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMcp(row.ID)
      ElMessage.success('删除成功')
      fetchMcpList()
    } catch (error) {
      // 错误已被拦截器处理
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  formErrors.value = []
  
  try {
    // 使用Element Plus表单验证
    await formRef.value.validate()
    
    // 开始提交
    submitting.value = true
    
    if (isEdit.value && editId.value !== null) {
      // 更新MCP
      await updateMcp(editId.value, mcpForm.value)
      ElMessage.success('更新MCP成功')
    } else {
      // 创建MCP
      await createMcp(mcpForm.value)
      ElMessage.success('创建MCP成功')
    }
    
    dialogVisible.value = false
    fetchMcpList()
    resetForm()
  } catch (error: any) {
    // 表单验证失败不需处理，接口错误已由拦截器处理
    if (!formErrors.value.length && !(error instanceof Error)) {
      formErrors.value.push(isEdit.value ? '更新MCP失败，请重试' : '创建MCP失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped lang="scss">
.mcp-manager {
  width: 100%;
}

/* 操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .search-wrapper {
    flex: 1;
    max-width: 500px;
    
    .search-input {
      position: relative;
      display: flex;
      align-items: center;
      
      .search-icon {
        position: absolute;
        left: 12px;
        color: #909399;
      }
      
      input {
        flex: 1;
        height: 40px;
        padding: 0 15px 0 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px 0 0 4px;
        font-size: 14px;
        
        &:focus {
          outline: none;
          border-color: #409eff;
        }
      }
      
      .search-btn {
        height: 40px;
        padding: 0 15px;
        border: none;
        border-radius: 0 4px 4px 0;
        background-color: #409eff;
        color: white;
        font-size: 14px;
        cursor: pointer;
        
        &:hover {
          background-color: #66b1ff;
        }
      }
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
    
    .btn-primary {
      display: flex;
      align-items: center;
      gap: 5px;
      height: 40px;
      padding: 0 15px;
      border: none;
      border-radius: 4px;
      background-color: #409eff;
      color: white;
      font-size: 14px;
      cursor: pointer;
      
      &:hover {
        background-color: #66b1ff;
      }
      
      .btn-icon {
        font-size: 16px;
      }
    }
  }
}

/* 表格卡片 */
.table-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  /* ID 列样式 */
  .user-id {
    font-weight: 600;
    background-color: #ecf3ff;
    color: #3a7cfe;
    padding: 4px 8px;
    border-radius: 4px;
    display: inline-block;
    min-width: 36px;
    text-align: center;
  }
  
  .table-actions {
    display: flex;
    gap: 8px;
    
    .action-btn {
      padding: 4px 8px;
      border: none;
      border-radius: 4px;
      font-size: 12px;
      cursor: pointer;
      
      &.btn-info {
        background-color: #e6f7ff;
        color: #1890ff;
        
        &:hover {
          background-color: #bae7ff;
        }
      }
      
      &.btn-success {
        background-color: #f6ffed;
        color: #52c41a;
        
        &:hover {
          background-color: #d9f7be;
        }
      }
      
      &.btn-warning {
        background-color: #fffbe6;
        color: #faad14;
        
        &:hover {
          background-color: #fff1b8;
        }
      }
      
      &.btn-danger {
        background-color: #fff2f0;
        color: #ff4d4f;
        
        &:hover {
          background-color: #ffccc7;
        }
      }
    }
  }
  
  .table-footer {
    padding: 15px;
    display: flex;
    justify-content: flex-end;
  }
}

/* 类型和状态标签 */
.type-badge, .status-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.type-stdio {
  background-color: #e6f7ff;
  color: #1890ff;
}

.type-sse {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-inactive {
  background-color: #f5f5f5;
  color: #909399;
}

/* 弹窗样式重构 */
.mcp-dialog {
  :deep(.el-dialog) {
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
  
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 0;
  }
  
  :deep(.el-dialog__headerbtn) {
    top: 16px;
    right: 16px;
    z-index: 10;
    
    .el-dialog__close {
      color: #ffffff;
      font-size: 16px;
      
      &:hover {
        color: #f2f2f2;
      }
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    padding: 12px 20px;
    border-top: 1px solid #ebeef5;
  }
  
  .dialog-custom-header {
    background: linear-gradient(135deg, #1a6fc4, #2b88d9);
    padding: 16px 20px;
    color: #ffffff;
    
    .header-title {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .title-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        height: 36px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        font-size: 18px;
      }
      
      .title-content {
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }
        
        p {
          margin: 2px 0 0;
          font-size: 13px;
          opacity: 0.8;
        }
      }
    }
  }
  
  .dialog-body {
    padding: 20px;
  }
  
  .form-errors {
    display: flex;
    gap: 10px;
    padding: 10px 12px;
    margin-bottom: 16px;
    background-color: #fff1f0;
    border: 1px solid #ffccc7;
    border-radius: 4px;
    
    .error-icon {
      color: #ff4d4f;
      font-size: 16px;
    }
    
    .error-list {
      flex: 1;
      
      .error-item {
        margin: 0;
        color: #ff4d4f;
        font-size: 13px;
        line-height: 1.5;
      }
    }
  }
  
  .mcp-form {
    .form-section {
      margin-bottom: 20px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 12px;
        padding-bottom: 6px;
        border-bottom: 1px solid #ebeef5;
      }
    }
    
    .form-row {
      display: flex;
      gap: 12px;
      margin-bottom: 6px;
      
      .form-item {
        flex: 1;
      }
    }
    
    :deep(.el-form-item) {
      margin-bottom: 14px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    :deep(.el-form-item__label) {
      padding-bottom: 4px;
      font-size: 13px;
      color: #606266;
      line-height: 1;
    }
    
    :deep(.el-input__inner) {
      height: 36px;
      line-height: 36px;
      border-radius: 4px;
      border-color: #dcdfe6;
      font-size: 13px;
      
      &:hover {
        border-color: #c0c4cc;
      }
      
      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
    
    :deep(.el-textarea__inner) {
      border-radius: 4px;
      padding: 6px 10px;
      line-height: 1.5;
      font-size: 13px;
      border-color: #dcdfe6;
      
      &:hover {
        border-color: #c0c4cc;
      }
      
      &:focus {
        border-color: #409eff;
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }
    
    .monospace-input {
      :deep(.el-textarea__inner) {
        font-family: 'Courier New', Courier, monospace;
        font-size: 12px;
        letter-spacing: -0.2px;
      }
    }
    
    .full-width {
      width: 100%;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    
    :deep(.el-button) {
      padding: 8px 16px;
      font-size: 13px;
    }
  }
}
</style> 